<?php
	// Get the get variables out of the link
	$race = $_GET['race'];
	$class = $_GET['class'];
	
	// Get the text database file contents out.
	$db = file('data.tdb');
	$db = array_map('trim', $db);

	// unserialize them back into their respective arrays.
	$classes = unserialize($db[0]);
	$roles = unserialize($db[1]);
	
	$output = '';
	
	// Echo out the playable class lists for the selected race to populate the class.
	if (isset($race)) {
		$output .= '<option>Select Class</option>';
		foreach ($classes[$race] as $tempclass) {
			$output .= '<option>' . $tempclass . '</option>';
		}
		//echo $output;
		die($output);
		
	}
	
	// Echo out the role lists for the selected class to populate the roles.
	if (isset($class)) {
		echo '<option value="">Select Role</option>';
		foreach ($roles[$class] as $role) {
			echo '<option>' . $role . '</option>';
		}
	}
	
	// Validation for adding/modifying members.
	function validate_member_data($membersFile, &$members, $data) {
		// Get the text database file contents out.
		$db = file_get_contents('tweaks/roster/data.tdb');
		$db = trim($db);
		
		// unserialize them back into their respective arrays.
		$db = unserialize($db);
		
		$classes = $db['races'];
		$specs = $db['classes'];
		
		// Validate and add the members details to the save file.
		$errmsg = '';
		$is_new = true;
		
		// Make the text entered data safe via htmlentities()
		$data['name'] = htmlentities($data['name']);
		$data['level'] = htmlentities($data['level']);
		
		// Format the name to lowercase with a captial first letter.
		$data['name'] = ucwords(strtolower($data['name']));
		
		// Name validation
		if (!ctype_alpha($data['name']) || (strlen($data['name']) > 12) || empty($data['name'])) {		
			// Invalid character name.
			$errmsg = $errmsg . 'Invalid Character Name<br />';
		}
		
		// Level validation
		if (!ctype_digit($data['level']) || ($data['level'] < 1 || $data['level'] > 80) || empty($data['level'])) {
			// Levels are numeric .
			$errmsg = $errmsg . 'Invalid Level<br />';
		}
		
		// Race Validation
		if (!array_key_exists($data['race'], $classes)) {
			$errmsg = $errmsg . 'Invalid Race Selection<br />';
		}
		
		// Class Validation
		if (empty($data['race'])|| empty($data['rclass'])) {
			$errmsg .= 'Invalid Class Selection<br />';
		}
		elseif (!in_array($data['rclass'], $classes[$data['race']])) {
			$errmsg = $errmsg . $data['race'] . 's cannot be a ' . $data['rclass'] . '<br />';
		}
		
		// Main Spec Validation
		if (!in_array($data['mainspec'], $specs[$data['rclass']])) {
			// Check for empty values for mainspec and previous selections
			if(empty($data['race']) || empty($data['rclass']) || empty($data['mainspec'])) {
				$errmsg = $errmsg . 'Invalid Main Spec Selection<br />';
			}
			else {
				$errmsg = $errmsg . $data['rclass'] . 's cannot be a ' . $data['mainspec'] . '<br />';
			}
		}
		
		// Off Spec Validation
		if ($data['offspec'] == 'None') {
			// Do nothing.
		}
		elseif (!in_array($data['offspec'], $specs[$data['rclass']])) {
			//Nothing selected or class doesn't play that role.
			if (empty($data['race']) || empty($data['rclass']) || empty($data['offspec'])) {
				$errmsg = $errmsg . 'Invalid Off Spec Selection<br />';
			}
			else {
				$errmsg = $errmsg . $data['rclass'] . 's cannot be a ' . $data['offspec'] . '<br />';
			}
		}
		
		// Gender Validation
		if (!isset($data['gender'])) {
			$errmsg .= 'Select a Gender<br />';
		}
		
		if (empty($errmsg)) {
			// Validation passes, retrive the members array from the save file and add the new member to the end and save it.
			if ($data['submit'] == 'Add') {
				// Adding a new member make sure it doesn't exist.
				foreach ($members as $mem) {
					// If the member already exists set is_new to false.
					if ($mem['name'] == $data['name']) {
						$is_new = false;
						$errmsg = 'Member exists.';
						break;
					}
				}
			}
			
			// Delete the old version of Member if modifying
			if ($data['submit'] == 'Modify') {
				if (isset($_GET['edit'])) {
					array_splice($members, $_GET['edit'], 1);
				}
			}
			
			if ($is_new) {
				$members[] = $data;
			
				// Unset the submit value.
				if (isset($data['submit'])) {
					unset($data['submit']);
				}
				
				// Sort the array by name.
				foreach($members as $mem) {
					// Put each name into a seperate array to use for the sort.
					$key[] = $mem['name'];
				}
				
				array_multisort($key, $members);
				
				// Put the updated content back into the file.
				$members = serialize($members);
				file_put_contents($membersFile, $members);

				// Wipe the post data if adding a new member so it doesn't redisplay
				if($_POST['submit'] == 'Add') {
					unset($_POST);
				}
				
				// Create the members page if it doesnt' exist.
				if (!file_exists('pages/members.php')) {
					$members_page = "<!-- Page auto-generated -->\n";
					$members_page .= "<?php runTweak('members-page'); ?>";
					
					file_put_contents('pages/members.php', $members_page);
					
					update_nanocms_pages('members');
				}
			}
		}
		
		return $errmsg;
	}
	
	// UI for adding/modifying members.
	function member_ui($data) {
		// Add the Javascript.
		echo '<script type="text/javascript" src="tweaks/roster/member.js"></script>';
		
		// Get the text database file contents out.
		$db = file('tweaks/roster/data.tdb');
		$db = array_map('trim', $db);

		// unserialize them back into their respective arrays.
		$classes = unserialize($db[0]);
		$roles = unserialize($db[1]);

		// Get the data for the select menus and radio buttons.
		$sel = ' selected="selected"';
		$chk = ' checked="true"';
		
		// Race selection.
		switch ($data['race']) {
			case 'Human':
				$rHum = $sel;
				break;
			case 'Dwarf':
				$rDwa = $sel;
				break;
			case 'Gnome':
				$rGno = $sel;
				break;
			case 'Night Elf':
				$rNel = $sel;
				break;
			case 'Draenei':
				$rDra = $sel;
				break;
			case 'Orc':
				$rOrc = $sel;
				break;
			case 'Troll':
				$rTro = $sel;
				break;
			case 'Tauren':
				$rTau = $sel;
				break;
			case 'Undead':
				$rUnd = $sel;
				break;
			case 'Blood Elf':
				$rBel = $sel;
				break;
		}
		
		// Class selection.
		switch ($data['rclass']) {
			case 'Death Knight':
				$cDK = $sel;
				break;
			case 'Druid':
				$cDru = $sel;
				break;
			case 'Hunter':
				$cHun = $sel;
				break;
			case 'Mage':
				$cMag = $sel;
				break;
			case 'Paladin':
				$cPal = $sel;
				break;
			case 'Priest':
				$cPri = $sel;
				break;
			case 'Rogue':
				$cRog = $sel;
				break;
			case 'Shaman':
				$cSha = $sel;
				break;
			case 'Warrior':
				$cWarr = $sel;
				break;
			case 'Warlock':
				$cWarl = $sel;
				break;
		}
		
		// Main Spec.
		switch ($data['mainspec']) {
			case 'DPS':
				$mDPS = $sel;
				break;
			case 'Healer':
				$mHeal = $sel;
				break;
			case 'Tank':
				$mTank = $sel;
				break;
		}
		
		// Off Spec.
		switch ($data['offspec']) {
			case 'None':
				$oNone = $sel;
				break;
			case 'DPS':
				$oDPS = $sel;
				break;
			case 'Healer':
				$oHeal = $sel;
				break;
			case 'Tank':
				$oTank = $sel;
				break;
		}
		
		// Gender Selection
		switch ($data['gender']) {
			case 'male':
				$gMal = $chk;
				break;
			case 'female':
				$gFem = $chk;
				break;
		}
		
		// UI
		$member_ui =  '<object>
				<ul>
					<li>
						<p><a href="?tweak=roster-tweak&r=Add">Add Member</a></p>
						<form name="member" action="" method="post">
							<table>
								<tr>
									<th>Name : </th>
									<td><input type="text" name="name" value="' . $data['name'] . '" maxlength="12" /></td>									
								</tr>
								<tr>
									<th>Level : </th>
									<td><input type="text" name="level" value="' . $data['level'] . '" maxlength="2" /></td>
								</tr>
								<tr>
									<th>Race : </th>
									<td>
										<select name="race">'."
											<option>Select Race</option>
											<optgroup label='Alliance'>
												<option value='Human'$rHum>Human</option>
												<option value='Dwarf'$rDwa>Dwarf</option>
												<option value='Gnome'$rGno>Gnome</option>
												<option value='Night Elf'$rNel>Night Elf</option>
												<option value='Draenei'$rDra>Draenei</option>
											</optgroup>
											<optgroup label='Horde'>
												<option value='Orc'$rOrc>Orc</option>
												<option value='Troll'$rTro>Troll</option>
												<option value='Tauren'$rTau>Tauren</option>
												<option value='Undead'$rUnd>Undead</option>
												<option value='Blood Elf'$rBel>Blood Elf</option>".'
											</optgroup>
										</select>
									</td>
								</tr>
								<tr>
									<th>Class : </th>
									<td>
										<select name="rclass" id="rclass">'."
											<option value=''>Select Class</option>
											<option value='Death Knight'$cDK>Death Knight</option>
											<option value='Druid'$cDru>Druid</option>
											<option value='Hunter'$cHun>Hunter</option>
											<option value='Mage'$cMag>Mage</option>
											<option value='Paladin'$cPal>Paladin</option>
											<option value='Priest'$cPri>Priest</option>
											<option value='Rogue'$cRog>Rogue</option>
											<option value='Shaman'$cSha>Shaman</option>
											<option value='Warrior'$cWarr>Warrior</option>
											<option value='Warlock'$cWarl>Warlock</option>".'
										</select>
									</td>
								</tr>
								<tr>
									<th>Main Spec : </th>
									<td>
										<select name="mainspec">'."
											<option value=''>Select Spec</option>
											<option value='DPS'$mDPS>DPS</option>
											<option value='Healer'$mHeal>Healer</option>
											<option value='Tank'$mTank>Tank</option>".'
										</select>
									</td>
								</tr>
								<tr>
									<th>Off Spec : </th>
									<td>
										<select name="offspec">'."
											<option value=''>Select Spec</option>
											<option value='None'$oNone>None</option>
											<option value='DPS'$oDPS>DPS</option>
											<option value='Healer'$oHeal>Healer</option>
											<option value='Tank'$oTank>Tank</option>".'
										</select>
									</td>
								</tr>
								<tr>
									<th rowspan="2">Gender : </th>
									<td><input type="radio" name="gender" id="male" value="male"' . $gMal . ' /><label for="male">Male</label></td>									
								</tr>								
								<tr>
									<td><input type="radio" name="gender" id="female" value="female"' . $gFem . ' /><label for="female">Female</label></td>
									
								</tr>
								<tr>
									<td><input type="submit" name="submit" value="' . $_GET['r'] . '" /></td>
								</tr>
							</table>
						</form>
					</li>
					<li><a href="?tweak=roster-tweak&r=Modify">Modify Members</a></li>
					<li><a href="?tweak=roster-tweak&r=New">New Roster</a></li>
					<li><a href="?tweak=roster-tweak&r=Modify_Roster">Modify Rosters</a></li>
				</ul>
			</object>';
			
			echo $member_ui;
	}
	
	// UI for picking members to modify or delete.
	function modify_ui($members) {
		$count = 0;
	
		echo '<object>
					<ul>
						<li><p><a href="?tweak=roster-tweak&r=Add">Add Member</a></p></li>
						<li>
							<p><a href="?tweak=roster-tweak&r=Modify">Modify Members</a></p>
							<table>
								<tr>
									<th>Name</th>
									<th>Class</th>
									<th>Level</th>
								</tr>';
								// Loop through the members array and print a row for each member.
								foreach ($members as $mem) {									
									echo '<tr>
											<td>'. $mem['name'] .'</td>
											<td>'. $mem['class'] .'</td>
											<td>'. $mem['level'] .'</td>
											<td><a href="?tweak=roster-tweak&r=Modify&edit='. $count .'">Modify</a></td>
											<td><a href="?tweak=roster-tweak&r=Modify&delete='. $count .'">Delete</a></td>
										</tr>';
									$count++;
								}
							echo '</table>
						</li>
						<li><p><a href="?tweak=roster-tweak&r=New">New Roster</a></p></li>
						<li><a href="?tweak=roster-tweak&r=Modify_Roster">Modify Rosters</a></li>
					</ul>
			</object>';
	}

	// Update NanoCMS's pages array
	function update_nanocms_pages($pagename) {
		// Check if the members page exists in the nano cms pagesdata array
		$pagesdata = file_get_contents('pagesdata.txt');
		$pagesdata = unserialize($pagesdata);
	
		$highkey = 0;
					
		foreach ($pagesdata['slugs'] as $key=>$value) {
			// members page exists
			if ($value == $pagename) {
				$found_page = true;
			}
			// Set highkey as the value of the highest key in the array.
			if( $highkey < $key ) {
				$highkey = $key;
			}
		}
		
		// Create the settings in NanoCMS's pages array.
		if (!$found_page) {
			$pagekey = $highkey + 1;
			
			// Add the values to the pages array.
			$pagesdata['slugs'][$pagekey] = $pagename;
			$pagesdata['titles'][$pagekey] = ucwords($pagename);
			
			// Add the pagekey value to the bottom of the sidebar menu.
			$pagesdata['links_cats']['sidebar'][] = $pagekey;
			
			$pagesdata = serialize($pagesdata);
			file_put_contents('pagesdata.txt', $pagesdata);
		}		
	}
?>